package com.tool.email;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2024/1/22 20:10
 * 邮件的优势在于免费
 */

public class EmailSendUtil {
    public static void main(String[] args) {
        try{
            send_email("2015981765@qq.com","这是一份测试邮件，无需回复！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void send_email(String email, String msg) throws IOException, AddressException, MessagingException {

        String to = email;	//接受人的邮件地址
        String subject = "有新留言!";	//邮件标题
        String content = msg;		//邮件内容
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.port", "25");
        properties.put("mail.smtp.auth", "true");
        Authenticator authenticator = new Email_Util("2578723602@qq.com", "nlwbksfnybvhecfi");//发送人的邮箱与授权码
        javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
        MimeMessage mailMessage = new MimeMessage(sendMailSession);
        mailMessage.setFrom(new InternetAddress("2578723602@qq.com"));//发送人的邮件地址
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mailMessage.setSubject(subject, "UTF-8");
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        html.setContent(content.trim(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
    }
}
